package taskq

import (
	"fmt"
	"sync"
	"time"
)

/**
* Author: dinglin
* Date: 2022/3/23 5:37 下午
 */

type (
	Task struct {
		TaskID   string
		StreamID string
		Name     string
		Delay    time.Duration
		Arg      []byte
	}
	TaskHandler struct {
		Handle  func(Arg []byte)
		Recover func()
	}
)

var (
	taskHandlerM sync.Map
)

func RegisterTaskHandler(name string, handler *TaskHandler) {
	if handler.Recover == nil {
		handler.Recover = DefaultRecover
	}
	_, has := taskHandlerM.LoadOrStore(name, handler)
	if has {
		panic(fmt.Sprintf("task(%s) already exists", name))
	}
}

func GetTask(name string) *TaskHandler {
	v, _ := taskHandlerM.Load(name)
	h, _ := v.(*TaskHandler)
	return h
}

func DefaultRecover() {
	_ = recover()
}
